﻿//全局变量
var table, myGrid, ised = "";

$(document).ready(function () {


    GetMenuButtonList('btnOp');
    //#region datatable初始化及值绑定
    $.extend($.fn.dataTable.defaults, {
        dom: 'rt<"#dt-bottom.row"<"col-xs-2"l><"col-xs-7"p><"col-xs-3"i>>'
    });
    var scrollY = document.body.clientHeight - 56 - 53 - 38 - 32 - 13 - 4;
    //适应窗口大小变化
    $(window).resize(function () {
        var newScrollY = document.body.clientHeight - 56 - 53 - 38 - 32 - 13 - 4;
        $('.dataTables_scrollBody').css('height', newScrollY);
    });
    myGrid = {
        id: 'dt_admin',
        isenable: false,//是否需要禁用启用按钮
        scrollY: scrollY,
        scrollX: true,
        paging: true,
        hasIndex: true,
        multiSelect: false,
        processing: true,
        serverSide: true,
        columns: [
                { data: "Row", title: "#" },
                { data: "code", title: "员工编号" },//"visible": false 
                { data: "name", title: "姓名" },
                { data: "sex", title: "性别" },
                { data: "part", title: "所属部门" },
                { data: "mobile", title: "手机号" },
                { data: "createtime1", title: "添加时间" }
        ],
        columnDefs: [
        {
            render: function (data, type, row) {
                return row.sex == 0 ? '男' : '女';
            },
            targets: [3]
        }],
        order: [[6, 'desc']],
        data: {},
        ajax: function (data, callback, settings) {
            //封装请求参数
            var reUrl = 'GetEmployees';
            var order = data.columns[data.order[0].column].data + " " + data.order[0].dir;
            var pagesize = data.length;
            var pageno = (data.start / data.length) + 1;
            //查询条件
            var searchData = { pagesize: pagesize, pageno: pageno, order: order, query: $('#query').val(), parts: $('#parts').val() };
            //ajax请求数据
            $.ajax({
                type: "GET",
                url: reUrl,
                cache: false,//禁用缓存
                data: searchData,//传入组装的参数
                dataType: "json",
                //headers: param,//请求头参数
                success: function (result, status, xhr) {
                    //封装返回数据
                    var returnData = {};
                    returnData.draw = data.draw; //这里直接自行返回了draw计数器,应该由后台返回
                    returnData.recordsTotal = result.TotalCount;
                    total_curr = result.TotalCurr;
                    returnData.recordsFiltered = result.TotalCount; //后台不实现过滤功能，每次查询均视作全部结果
                    returnData.data = result.Entity; //返回的数据列表
                    //调用DataTables提供的callback方法，代表数据已封装完成并传回DataTables进行渲染
                    //此时的数据需确保正确无误，异常判断应在执行此回调前自行处理完毕
                    callback(returnData);//将你的返回的data转为datatables能识别的数据格式作为参数返回ajax的callback回调中。
                }
            });
        }
    }
    table = DataBind(myGrid);
    $('#datetimepicker_start').datetimepicker({
        format: 'YYYY-MM-DD'
    });
    $('#btnInquire').click(function () {
        loadTableData();
    })

    //#endregion 

    $('#btnCardSave').click(function () {
        AjaxSave();
    });
});


//新增
var Btn_Add = function () {
    $('#title').text("新增会员");
    $('#id').val('-1'); 
    $("#code").val('');
    $("#name").val('');
    $("#sex").val('');
    $("#depart").val('');
    $("#mobile").val('');
    $("#createtime").val('');

    $('#InsuranceAccountAddModal').modal('show');
}

//编辑
var Btn_Edit = function () {
    if (table.rows('.selected').data().length == 0) {
        $.notify({
            message: '<i class="fa fa-bell-o"></i> 请选中要编辑的数据！',
            status: "info",
            group: null,
            pos: "bottom-right"
        });
        return;
    }
    var seletedItem = table.rows('.selected').data()[0];
    $('#title').text("会员编辑");
    $("#id").val(seletedItem.id);
    $("#code").val(seletedItem.code);
    $("#name").val(seletedItem.name);
    $("#sex").val(seletedItem.sex);
    $("#depart").val(seletedItem.depart);

    $('#InsuranceAccountAddModal').modal('show');
}

//刷新datatable
function loadTableData() {
    table.ajax.reload();
}

function GetValues() {
    var obj = {};
    obj.id = $("#id").val();
    obj.code = $("#code").val();
    obj.name = $("#name").val();
    obj.sex = $("#sex").val();
    obj.depart = $("#depart").val();
    obj.mobile = $("#mobile").val();
    return obj;
}

function AjaxSave() {
    $.ajax({
        type: "post",
        contentType: "application/json;utf-8",
        url: "SaveEmployee?t=" + new Date().getTime(),
        data: "{json:'" + $.toJSON(GetValues()) + "'}",
        success: function (result) {
            result = eval('(' + result + ')');
            $.notify({
                message: '<i class="fa ' + (result.IsSucceed ? 'fa-check' : 'fa-exclamation') + '"></i> ' + result.Message,
                status: result.IsSucceed ? 'success' : "danger",
                pos: "bottom-right"
            });
            if (result.IsSucceed) {
                $('#InsuranceAccountAddModal').modal('hide');
                loadTableData(myGrid);
            }
            else {
                if (result.Entity != "" && result.Entity != null)
                    window.parent.location.href = result.Entity;
            }
        }
    });
}
//删除
var Btn_Delete = function () {
    if (table.rows('.selected').data().length == 0) {
        $.notify({
            message: '<i class="fa fa-bell-o"></i> 请选择要删除的数据！',
            status: "info",
            group: null,
            pos: "bottom-right"
        });
        return;
    }
    bconfirm("确定删除？", LogDelete);
}
//删除方法
function LogDelete() {
    var ids = [];
    for (var i = 0; i < table.rows('.selected').data().length; i++) {
        ids.push(table.rows('.selected').data()[i].id);
    }
    $.ajax({
        type: "post",
        contentType: "application/json;utf-8",
        url: "DeleteEmployee?ids=" + ids.join() + "&t=" + new Date().getTime(),
        data: "",
        success: function (result) {
            result = eval('(' + result + ')');
            $.notify({
                message: '<i class="fa ' + (result.IsSucceed ? 'fa-check' : 'fa-exclamation') + '"></i> ' + result.Message,
                status: result.IsSucceed ? 'success' : "danger",
                pos: "bottom-right"
            });
            if (result.IsSucceed) {
                loadTableData(myGrid);
            }
            else {
                if (result.Entity != "" && result.Entity != null)
                    window.parent.location.href = result.Entity;
            }
        }
    });
}
